from typing import List, TYPE_CHECKING, Union, Callable, ClassVar,Optional
from pydantic import EmailStr
from datetime import datetime
from sqlmodel import  SQLModel,text,Column,TEXT,Field,Relationship
from .base import SQLModelBase
from .resBase import BaseResponse
import sqlalchemy as sa



if TYPE_CHECKING:    
    from .user import User

# 用户帖子模型
class ArticleBase(SQLModel):                  
    content: str | None = Field( default=None, title="内容",sa_column=Column(TEXT, comment="内容"  ))
    images: str | None = Field( default=None, title="图片",sa_column=Column(TEXT, comment="图片路径,用逗号分割"  ))
    topics: str | None = Field( default=None, title="话题",sa_column=Column(TEXT, comment="话题标签,用逗号分割"  ))
    


class Article(ArticleBase,SQLModelBase, table=True):
    userId: int = Field(foreign_key="users.id",sa_column_kwargs={"comment": "用户唯一id","name":"user_id"})    

    # 定义表参数
    __tablename__: str = "articles" 
    __table_args__ = {'comment': '用户动态'}
    user:"User" = Relationship(back_populates="articles")
    likes: List["Like"] = Relationship(back_populates="article")
    comments: List["Comment"] = Relationship(back_populates="article")

class Like(SQLModelBase, table=True):    
    userId: int = Field(foreign_key="users.id",sa_column_kwargs={"comment": "用户唯一id","name":"user_id"})    
    articleId: int = Field(foreign_key="articles.id",sa_column_kwargs={"comment": "帖子id","name":"article_id"})    
    
    # 定义表参数
    __tablename__: str = "likes" 
    __table_args__ = {'comment': '用户点赞'}
    
    article: "Article" = Relationship(back_populates="likes")

class Comment( SQLModelBase,table=True):
    
    content: str | None = Field( default=None, title="内容",sa_column=Column(TEXT, comment="内容"  ))
    images: str | None = Field( default=None, title="图片",sa_column=Column(TEXT, comment="图片路径,用逗号分割"  ))
    
    userId: int = Field(foreign_key="users.id",sa_column_kwargs={"comment": "用户唯一id","name":"user_id"})    
    articleId: int = Field(foreign_key="articles.id",sa_column_kwargs={"comment": "帖子id","name":"article_id"})    
    parentId: int | None = Field(
        default=None, 
        foreign_key="comments.id",
        sa_column_kwargs={
            "comment": "父评论id",
            "name":"parent_id",
            "nullable": True
        }
    )
    
    # 定义表参数
    __tablename__: str = "comments" 
    __table_args__ = {'comment': '用户评论'}
    
    article: "Article"  = Relationship(back_populates="comments")
    # 添加自引用关系
    parent: "Comment" = Relationship(
        back_populates="children",
        sa_relationship_kwargs={'remote_side': 'Comment.id'}
    )
    children: List["Comment"] = Relationship(back_populates="parent")